package com.mindata.blockmanager.handler;

import com.mindata.blockmanager.bean.BaseData;
import com.mindata.blockmanager.bean.ResultCode;
import com.mindata.blockmanager.bean.ResultGenerator;
import com.mindata.blockmanager.exception.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 全局异常捕获处理类
 */
@ControllerAdvice
@Slf4j
public class AppExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseData handle(HttpServletRequest request, HttpServletResponse response, Exception e) {
        //业务异常
        if (e instanceof BlockException) {
            BlockException blockException = (BlockException) e;
            log.error("业务异常 ======>{}", blockException.getRtnMsg());
            return ResultGenerator.genFailResult(blockException.getRtnCd(), blockException.getMessage());
        } else {
            //系统异常
            log.error("系统异常 ======>", e);
            return ResultGenerator.genFailResult(String.valueOf(ResultCode.SYSTEM_ERROR.code), e.getMessage());
        }
    }
}
